package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.*;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyJiShiYouXuan;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeJiShiYouXuan;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiProtocol;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 安心出-及时优享 全流程28分润
 * <a href="https://mvfhxey0lul.feishu.cn/wiki/KBxiwcZ0ViIKc9kF3uVcLThdnTb?fromScene=spaceOverview">...</a>
 *
 * @author 李源聪
 * @since 2025/5/21 17:13
 */
@ApiPlan(productId = "408", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatJiShiYouXuanPhoneMd5 implements ApiPlatformPhoneMd5ConvertHandler {
    private static final String KEY = "zf7mts2pytrekxjy";
    private static final String CHANNEL_CODE = "AXFQ_CD";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        // 实体类
        ApiPlatDataExchangeJiShiYouXuan data = new ApiPlatDataExchangeJiShiYouXuan();
        //拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 获得手机号,小写
        data.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        //  年龄
        data.setAge(apiFieldConverter.getAgeInt());
        //  城市名称
        data.setCity(apiDataExchangeParameter.getCity());
        // 城市编码
        data.setCityCode(apiDataExchangeParameter.getAreaCode());
        //  性别 1男 2女 0 未知
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "2", 0)
                .end(0);
        data.setGender(sex);
        // 贷款时间 2(6个月)3(12个月)4(24个月)5(36个月)
        Integer time = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 3)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 4)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 5)
                .end(2);
        data.setLoanTime(time);
        //  职业  1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）
        Integer career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 2)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 4)
                .when(apiDataExchangeParameter.getCareer(), "5", 2)
                .end(1);
        data.setProfession(career);
        //  芝麻分 1（550分以下）2（550-600） 3（600-650）4（650-700）5（700以上）6（无）
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 4)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 5)
                .end(6);
        data.setZhima(zhima);
        //  公积金 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 4)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(4);
        data.setProvidentFund(providentFund);
        //  社保 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 4)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(4);
        data.setSocialSecurity(socialSecurity);
        // 保单 0（6个月以下）1（6-12个月）2（12个月以上）3（无）
        Integer commericalInsurance = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        data.setCommericalInsurance(commericalInsurance);

        //  房产 1:有 2:无
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        data.setHouse(house);
        // 逾期记录1（信用良好）2（1年内逾期≤3次）2（1年内逾>3次）
        Integer overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 1)
                .end(1);
        data.setOverdue(overdue);
        //  车产 1:有 2:无
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(2);
        data.setVehicle(vehicle);
        //  贷款额度 贷款金额（元）
        data.setLoanAmount(apiFieldConverter.getLoanAmountInt());
        Integer huaBei = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 3)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 2)
                .end(1);
        data.setHuabei(huaBei);
        Integer baiTiao = ChooseEq.create()
                .when(apiDataExchangeParameter.getBtLimit(), "1", 1)
                .when(apiDataExchangeParameter.getBtLimit(), "2", 3)
                .when(apiDataExchangeParameter.getBtLimit(), "3", 2)
                .when(apiDataExchangeParameter.getBtLimit(), "4", 2)
                .end(1);
        data.setBaitiao(baiTiao);
        // 信用卡额度 1 (1万元以下) 2 (1万-3万) 3 (3万以上) 4 (无信用卡)
        Integer creditCard = ChooseEq.create()
                .when(apiDataExchangeParameter.getCreditLimit(), "1", 4)
                .when(apiDataExchangeParameter.getCreditLimit(), "2", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "3", 1)
                .when(apiDataExchangeParameter.getCreditLimit(), "4", 2)
                .when(apiDataExchangeParameter.getCreditLimit(), "5", 3)
                .when(apiDataExchangeParameter.getCreditLimit(), "6", 3)
                .end(4);
        data.setCreditCard(creditCard);
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("timestamp", System.currentTimeMillis());
            newMap.put("reqId", apiDataExchangeParameter.getReqId());
            newMap.put("data", dataStr);
            newMap.put("channelCode", CHANNEL_CODE);
        });
        return JsonUtils.toJson(map);
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        ApiPlatApplyJiShiYouXuan data = new ApiPlatApplyJiShiYouXuan();
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 姓名
        data.setName(apiApplyParameter.getUserName());
        // 手机号
        data.setPhone(apiApplyParameter.getPhone());
        //  城市名称
        data.setCity(apiApplyParameter.getCity());
        // 城市编码
        data.setCityCode(apiApplyParameter.getAreaCode());
        data.setAge(apiFieldConverter.getAgeInt());
        data.setIdCard(apiApplyParameter.getIdcard());
        //  性别 1男 2女 0 未知
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "2", 0)
                .end(0);
        data.setGender(sex);
        // 贷款时间 2(6个月)3(12个月)4(24个月)5(36个月)
        Integer time = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "2", 2)
                .when(apiApplyParameter.getLoanTerm(), "3", 3)
                .when(apiApplyParameter.getLoanTerm(), "4", 4)
                .when(apiApplyParameter.getLoanTerm(), "5", 5)
                .end(2);
        data.setLoanTime(time);
        //  职业  1(上班族) 2（自由职业）3（私营企业主）4（公务员/国企）
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 2)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 4)
                .when(apiApplyParameter.getCareer(), "5", 2)
                .end(1);
        data.setProfession(career);
        //  芝麻分 1（550分以下）2（550-600） 3（600-650）4（650-700）5（700以上）6（无）
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 2)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 4)
                .when(apiApplyParameter.getSesameCredit(), "4", 5)
                .end(6);
        data.setZhima(zhima);
        //  公积金 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 4)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(4);
        data.setProvidentFund(providentFund);
        //  社保 1:6个月以下 2:6-12个月 3:12个月以上 4:无
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 4)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(4);
        data.setSocialSecurity(socialSecurity);
        // 保单 0（6个月以下）1（6-12个月）2（12个月以上）3（无）
        Integer commericalInsurance = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 3)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        data.setCommericalInsurance(commericalInsurance);

        //  房产 1:有 2:无
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        data.setHouse(house);
        // 逾期记录1（信用良好）2（1年内逾期≤3次）2（1年内逾>3次）
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 1)
                .end(1);
        data.setOverdue(overdue);
        //  车产 1:有 2:无
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 2)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 1)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(2);
        data.setVehicle(vehicle);
        //  贷款额度 贷款金额（元）
        data.setLoanAmount(apiFieldConverter.getLoanAmountInt());
        Integer huaBei = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 1)
                .when(apiApplyParameter.getSesameCredit(), "2", 3)
                .when(apiApplyParameter.getSesameCredit(), "3", 2)
                .when(apiApplyParameter.getSesameCredit(), "4", 2)
                .end(1);
        data.setHuabei(huaBei);
        Integer baiTiao = ChooseEq.create()
                .when(apiApplyParameter.getBtLimit(), "1", 1)
                .when(apiApplyParameter.getBtLimit(), "2", 3)
                .when(apiApplyParameter.getBtLimit(), "3", 2)
                .when(apiApplyParameter.getBtLimit(), "4", 2)
                .end(1);
        data.setBaitiao(baiTiao);
        // 信用卡额度 1 (1万元以下) 2 (1万-3万) 3 (3万以上) 4 (无信用卡)
        Integer creditCard = ChooseEq.create()
                .when(apiApplyParameter.getCreditLimit(), "1", 4)
                .when(apiApplyParameter.getCreditLimit(), "2", 1)
                .when(apiApplyParameter.getCreditLimit(), "3", 1)
                .when(apiApplyParameter.getCreditLimit(), "4", 2)
                .when(apiApplyParameter.getCreditLimit(), "5", 3)
                .when(apiApplyParameter.getCreditLimit(), "6", 3)
                .end(4);
        data.setCreditCard(creditCard);
        data.setIp(apiApplyParameter.getIp());
        data.setAgreeProtocol(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        AES aes = AES.createEcb(KEY.getBytes());
        String dataStr = aes.encryptToBase64Str(JsonUtils.toJson(data));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("timestamp", System.currentTimeMillis());
            newMap.put("reqId", apiApplyParameter.getReqId());
            newMap.put("data", dataStr);
            newMap.put("channelCode", CHANNEL_CODE);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = jsonObject.getJSONObject("data");

        BigDecimal price = resData.getBigDecimal("price");
        String orderId = jsonObject.getString("productId");
        JSONObject product = resData.getJSONObject("product");
        String productName = product.getString("prodName");
        String logo = product.getString("prodLogo");
        List<ApiProtocol> protocolList = CollUtils.newArrayList(newList -> {
            //  获取协议
            JSONArray listProtocolResult = resData.getJSONArray("protocalList");
            IteratorUtils.array(listProtocolResult, (item, index) -> {
                JSONObject protocolObject = listProtocolResult.getJSONObject(index);
                ApiProtocol protocol = new ApiProtocol();
                protocol.setProtocolName(protocolObject.getString("protoName"));
                protocol.setProtocolUrl(protocolObject.getString("protoUrl"));
                newList.add(protocol);
            });
        });

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setProtocolList(protocolList);
        result.setPrice(price);
        result.setLogoPath(logo);
        result.setApplyId(orderId);
        result.setDisplayName("及时优享");
        result.setProductName(productName);
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
